<template>
	<view class="login">
		<uni-nav-bar @clickRight="$tab.nav(`/pages/register`)" :status-bar="true" :fixed="true" :border="false"
			background-color="transparent" color="#FFF">
			<!-- #ifndef MP-WEIXIN -->
			<block slot="right">
				注册
			</block>
			<!-- #endif -->
		</uni-nav-bar>

		<view class="logo flex justify-around items-center" :style="{
			background: `url(${globalConfig.appConfig.loginBg})`,
			backgroundSize: '100% 100%'
		}">
			<image :src="globalConfig.appConfig.loginIcon" class="logo-img" mode="widthFix"></image>
		</view>

		<view class="px-20 content">
			<view class="login-text font-700">
				欢迎登录
			</view>

			<!-- #ifndef MP-WEIXIN -->
			<view class="" style="margin-top: 100rpx;">
				<u--form labelPosition="left" :model="loginForm" :rules="loginFormRules" ref="loginFormRules"
					label-width="110rpx">
					<u-form-item label="手机号" prop="username" borderBottom>
						<u--input v-model="loginForm.username" placeholder="请输入账号" border="none"></u--input>
					</u-form-item>
					<u-form-item label="验证码" prop="code" borderBottom v-if="loginType == 2">
						<u--input v-model="loginForm.code" border="none" placeholder="请填写验证码"></u--input>
						<u-button slot="right" @tap="getCode" :text="tips" size="mini"></u-button>
					</u-form-item>
					<u-form-item label="密码" prop="password" borderBottom v-else>
						<u--input type="password" v-model="loginForm.password" border="none"
							placeholder="密码"></u--input>
					</u-form-item>
				</u--form>
			</view>

			<view class="mt-28 text-9E9E9E" @click="loginType = loginType == 1 ? 2 : 1">
				{{ loginType == 1 ? '验证码登录' : '密码登录' }}
			</view>

			<view class="" style="margin-top: 100rpx;">
				<button class="login-btn" @click="pwdLogin">立即登录</button>
				<view class="flex mt-48 justify-around">
					<view class="text-20 forget" @click="$tab.nav(`/pages/forgetPassword`)">
						忘记密码
					</view>
				</view>
			</view>
			<!-- #endif -->


			<!-- #ifdef MP-WEIXIN -->
			<view class="" style="margin-top: 100rpx;">
				<button class="login-btn" @click="mpWxLogin">登录</button>
				<button class="login-btn-cancel" @click="cancelLogin">取消登录</button>
			</view>
			<!-- #endif -->

			<view class="mt-48 flex align-center justify-around">
				<view class="flex align-center">
					<u-checkbox-group @change="checkedChange" active-color="#F53A1E">
						<u-checkbox v-model="checked" shape="square"></u-checkbox>
					</u-checkbox-group>
					<text class="text-grey1">请认真阅读并勾选</text>
					<text @click="handleUserAgrement" class="">《用户协议》</text>
					<text @click="handlePrivacy" class="">《隐私协议》</text>
				</view>
			</view>
		</view>

		<!-- s APP版本更新 -->
		<update ref="myUpdataModel"></update>
		<!-- E APP版本更新-->

		<u-code ref="uCode" @change="codeChange" seconds="60">
		</u-code>

		<!-- #ifdef MP-WEIXIN -->
		<u-popup :show="loginShow" mode="bottom" @close="loginShow = false" :round="24">
			<view class="login-form py-28 px-32">
				<view class="flex items-center justify-between">
					<view class="font-700">
						富乐万家申请使用
					</view>
					<u-icon name="close" :bold="true" @click="loginShow = false"></u-icon>
				</view>
				<view class="text-40 font-700 mt-32">
					您的手机号及头像昵称
				</view>
				<u-divider></u-divider>
				<view class="flex items-center">
					<view class="">
						头像
					</view>
					<button class="avatar-wrapper round" open-type="chooseAvatar" @chooseavatar="onChooseAvatar">
						<image class="w-full round" mode="widthFix" :src="loginForm.avatar"></image>
					</button>
				</view>
				<u-divider></u-divider>
				<view class="flex items-center">
					<view class="">
						昵称
					</view>
					<input type="nickname" class="nickName px-32" placeholder="请输入昵称" v-model="loginForm.nickName" />
				</view>
				<u-divider></u-divider>
				<view class="flex items-center">
					<view class="">
						手机号
					</view>
					<button open-type="getPhoneNumber" @getphonenumber="getphonenumber" class="get-phone">
						{{ loginForm.phoneCode ? loginForm.phoneCode : '点击绑定手机号' }}
					</button>
				</view>
				<u-divider></u-divider>
				<view class="login-form-btn text-center text-FFF" @click="loginConfirm">
					确认
				</view>
			</view>
		</u-popup>
		<view class="webViewPage" v-if="showWebViewPage">
			<web-view :progress="true" :webview-styles="webviewStyles" :src="pageUrl" @load="loadSuccess"></web-view>
		</view>
		<!-- #endif -->
	</view>
</template>

<script>
import update from '@/components/update/update'
import {
	setToken,
	getToken
} from "@/utils/auth.js"
export default {
	components: {
		update
	},
	data() {
		return {
			globalConfig: getApp().globalData.config,
			loginForm: {
				username: "",
				password: "",
				loginWay: 1,
				code: "",
				verifyCode: "",
				uuid: ""
			},
			checked: "",
			loginType: 1, //登录类型 1密码登录 2验证码登录
			tips: "获取验证码",
			loginFormRules: {
				username: {
					required: true,
					message: '请输入账号',
					trigger: ['blur', 'change']
				},
				password: {
					required: true,
					message: '请输入密码',
					trigger: ['blur', 'change']
				},
				code: {
					required: true,
					message: '请输入验证码',
					trigger: ['blur', 'change']
				}
			},
			loginShow: false,
			openId: null,
			loginForm: {
				avatar: null,
				nickName: null,
			},
			showWebViewPage: false,
			pageUrl: null
		}
	},
	onLoad() {
		uni.hideTabBar()
		//#ifdef APP
		if (process.env.NODE_ENV === 'development') {
			console.log('开发环境');
		} else {
			this.$nextTick(() => {
				this.$refs.myUpdataModel.updateVersion()
			})
		}
		//#endif
	},
	onReady() {
		// #ifndef MP-WEIXIN
		this.$refs.loginFormRules.setRules(this.loginFormRules)
		// #endif
	},
	methods: {
		// #ifdef MP-WEIXIN
		cancelLogin() {
			uni.switchTab({
				url: '/pages/indexPage'
			})
		},
		mpWxLogin() {
			if (this.checked.length == 0) {
				uni.$u.toast('请先同意用户协议，隐私协议');
				return false
			}
			uni.login({
				provider: "weixin",
				success: (e) => {
					this.$Api.user.mpWxLogin({
						code: e.code
					}).then(wxlogin => {
						if (wxlogin.userInfo.phonenumber) {
							setToken(wxlogin.token)
						}
						this.openId = wxlogin.userInfo.openId
						this.loginForm = {
							avatar: wxlogin.userInfo.avatar,
							nickName: wxlogin.userInfo.nickName,
							phoneCode: wxlogin.userInfo.phonenumber
						}
						this.loginShow = true
						uni.hideLoading()
					})
				}
			})
		},
		async onChooseAvatar(e) {
			uni.showLoading({
				title: '加载中...'
			})
			const res = await this.$Api.common.uploadFile(e.detail.avatarUrl)
			this.loginForm.avatar = res.url
			uni.hideLoading()
		},
		async loginConfirm() {
			if (!getToken()) {
				this.$modal.msg('请绑定手机号!')
				return
			}
			if (this.loginForm.avatar || this.loginForm.nickName) {
				let form = {}
				if (this.loginForm.nickName) {
					form.nickName = this.loginForm.nickName
				}
				if (this.loginForm.avatar) {
					form.avatar = this.loginForm.avatar
				}
				this.$Api.user.updateUserInfo(form).then(res => {
					this.$store.dispatch('GetInfo')
				})
			}
			this.loginShow = false;
			if (uni.getStorageSync('commodity')) {
				uni.reLaunch({
					url: '/pages/commodity/detail'
				})
			} else {
				this.getYujiId()
				// uni.reLaunch({
				// 	url: '/pages/indexPage'
				// })
			}
		},
		getphonenumber(e) {
			this.$Api.user.mpMobileLogin({
				code: e.detail.code,
				openid: this.openId
			}).then(res => {
				setToken(res.token)
				this.$store.dispatch('GetInfo')
				this.loginForm.phoneCode = res.userInfo.phonenumber
			})
		},

		// #endif
		codeChange(text) {
			this.tips = text;
		},
		getCode() {
			var that = this;
			if (this.loginForm.username.trim() === '') {
				this.$modal.msgError("请输入手机号")
				return false
			}
			if (uni.$u.test.mobile(this.loginForm.username.trim()) === false) {
				this.$modal.msgError("请输入正确的手机号")
				return false
			}
			if (this.$refs.uCode.canGetCode) {
				// 模拟向后端请求验证码
				uni.showLoading({
					title: '正在获取验证码'
				})
				that.$Api.common.sendSms(that.loginForm.username).then(res => {
					that.loginForm.uuid = res.data;
					uni.hideLoading();
					// 这里此提示会被this.start()方法中的提示覆盖
					uni.$u.toast('验证码已发送');
					// 通知验证码组件内部开始倒计时
					that.$refs.uCode.start();
					that.$modal.closeLoading();
				}).catch(() => {
					that.$modal.closeLoading();
				})
			} else {
				uni.$u.toast('倒计时结束后再发送');
			}
		},
		checkedChange(e) {
			this.checked = e
		},
		// 隐私协议
		handlePrivacy() {
			let site = this.globalConfig.appInfo.agreements[5]
			this.$tab.nav(`/pages/common/webview/index?title=${site.title}&url=${site.url}`)
		},
		// 用户协议
		handleUserAgrement() {
			let site = this.globalConfig.appInfo.agreements[6]
			this.$tab.nav(`/pages/common/webview/index?title=${site.title}&url=${site.url}`)
		},
		loadSuccess() {
			setTimeout(() => {
				uni.reLaunch({
					url: '/pages/indexPage'
				})
			}, 4000);
		},
		getYujiId() {
			let userInfo = this.$store.getters.userInfo;
			let isWeixin = this.$wechat.isWeixin;
			const source = 51;
			const HTTP_REQUEST_URL = "https://api.fulewanjia.com"
			const yj_user_notify_url = "/fulewanjia/ws/appUser/yjUser";
			// /api/front / login / yjUser
			if (!userInfo.yjUserId) {
				// 去绑定予集ID
				// #ifdef H5
				if (isWeixin) {
					let url = `https://dc.yjmt191314.com/pages/users/login/wxlogin?source=${source}&foreign_id=${userInfo.userId}&callback_url=${HTTP_REQUEST_URL}&callback_fun=${yj_user_notify_url}&platform=h5&userurl=/pages/user/index`
					window.location.href = url
				} else {
					this.$util.Tips({
						title: '请在微信公众号中登录以提供完整服务'
					});
				}
				// #endif
				// #ifdef MP-WEIXIN
				this.pageUrl = `https://dc.yjmt191314.com/pages/users/login/wxlogin?source=${source}&foreign_id=${userInfo.userId}&callback_url=${HTTP_REQUEST_URL}&callback_fun=${yj_user_notify_url}&platform=wx&userurl=/pages/user/index`
				this.showWebViewPage = true;
				// uni.navigateTo({
				// 	url: `/pages/annex/web_view/yjAttestation?url=${url}&source=${source}&foreign_id=${userInfo.userId}&callback_url=${HTTP_REQUEST_URL}&callback_fun=${yj_user_notify_url}&platform=wx&userurl=/pages/user/index`,
				// });
				// #endif
				// #ifdef APP-PLUS
				plus.share.getServices(services => {
					const wxService = services.find(item => item.id === 'weixin');
					if (!wxService) {
						uni.showToast({ title: '请安装微信客户端', icon: 'none' });
						return;
					}
					console.log(`pages/users/login/wxlogin?source=${source}&foreign_id=${userInfo.userId}&callback_url=${HTTP_REQUEST_URL}&callback_fun=${yj_user_notify_url}&platform=app&userurl=/pages/user/index`)
					wxService.launchMiniProgram({
						id: 'gh_553e492fab19',      // 微信小程序的原始ID（非AppID）
						path: `pages/users/login/wxlogin?source=${source}&foreign_id=${userInfo.userId}&callback_url=${HTTP_REQUEST_URL}&callback_fun=${yj_user_notify_url}&platform=app&userurl=/pages/user/index`, // 目标页面路径，不传默认首页
						type: 0             // 0-正式版，1-测试版，2-体验版
					}, res => {
						// 小程序返回App时的回调（可接收参数）
						console.log('返回参数:', res);
					}, err => {
						console.error('跳转失败:', err);
					});
				}, err => {
					console.error('获取分享服务失败:', err);
				})
				// #endif
			} else {
				uni.reLaunch({
					url: '/pages/indexPage'
				})
			}
		},
		// 密码登录
		async pwdLogin() {
			if (this.checked.length == 0) {
				uni.$u.toast('请先同意用户协议，隐私协议');
				return false
			}
			if (this.loginType == 1) {
				this.$store.dispatch('Login', this.loginForm).then(() => {
					// 设置用户信息
					this.$store.dispatch('GetInfo').then(res => {
						console.log("🚀🚀🚀 ~ this.$store.dispatch ~ res:", res)
						this.getYujiId();
						this.$tab.reLaunch('/pages/indexPage')
					})
				})
			} else {
				let form = {
					phonenumber: this.loginForm.username,
					code: this.loginForm.code,
					uuid: this.loginForm.uuid
				}
				this.$Api.user.smsLogin(form).then(res => {
					console.log('验证登录', res)
					setToken(res.token)
					this.$store.dispatch('GetInfo').then(info => {
						uni.switchTab({
							url: '/pages/indexPage'
						})
					})
				})
			}
		},
	}
}
</script>

<style lang="scss">
page {
	background-color: #ffffff;
}

/deep/ .uni-navbar {
	width: 100%;
	position: fixed;
	left: 0;
	top: 0;
	z-index: 9;
}

.logo {
	width: 100%;
	height: 480rpx;

	.logo-img {
		width: 208rpx;
	}
}

.login-text {
	font-size: 56rpx;
	background-image: linear-gradient(to bottom,
			#ff561d,
			#ff0064);
	/* 从左到右的红色至黄色线性渐变 */
	background-clip: text;
	-webkit-background-clip: text;
	/* Safari/Chrome特定样式，将渐变应用于文字区域 */
	-webkit-text-fill-color: transparent;
	/* Safari/Chrome特定样式，透明化文字内容 */
}

.login-btn {
	background: linear-gradient(180deg, #FF561D 33%, #FF0064 100%);
	color: #fff;
	border-radius: 278rpx 278rpx 278rpx 278rpx;

	&::after {
		border: none !important;
	}
}

.login-btn-cancel {
	margin-top: 40rpx;
	border-radius: 278rpx 278rpx 278rpx 278rpx;

	&::after {
		border: none !important;
	}
}

.forget {
	border-bottom: 2rpx solid #000;
	padding-bottom: 4rpx;
	color: #666666;
}

.content {
	padding-top: 90rpx;
	border-radius: 64rpx 64rpx 0 0;
	position: relative;
	top: -64rpx;
	z-index: 9;
	width: 100%;
	background-color: #FFF;
}


/deep/ .u-button--info {
	border: none !important;
	color: #FFB200;
}

/deep/ .u-form-item__body {
	padding: 32rpx 0 !important;
}

.login-form {
	.avatar-wrapper {
		width: 64rpx;
		height: 64rpx;
		padding: 0;
		margin: 0;
		margin-left: 24rpx;
	}

	.login-form-btn {
		width: 448rpx;
		height: 80rpx;
		background: #333333;
		border-radius: 8rpx 8rpx 8rpx 8rpx;
		line-height: 80rpx;
		margin: 56rpx auto 0;
	}

	.get-phone {
		font-size: 28rpx;
		margin: 0;
		margin-left: 24rpx;
		background: none;
		color: #28AA17;
	}
}
</style>